<template>
  <view class="container px-2 py-1">
    <!-- 俱乐部或商家全称 -->
    <view class="form-row py-1 d-flex-between">
      <view class="label" >
        <text class="colorprice">*</text>
        <text class="color666  font30">名称：</text>
      </view>
      <input v-model="form.name" maxlength="8" placeholder="请输入俱乐部或商家全称" confirm-type="done"/>
    </view>

    <!-- 统一社会信用代码 -->

      <view class="form-row py-1 d-flex-between">
        <view class="label" >
          <text class="colorprice">*</text>
          <text class="color666  font30">税号：</text>
        </view>
        <input
            type="text"
            inputmode="text"
            v-model="form.tax_number"
            placeholder="请输入统一社会信用代码"
            confirm-type="done"
        />
    </view>

    <!-- 证件 -->
    <view class="photo-section py-4">
      <text class="section-title font30 pb-3"><text class="colorprice">*</text>证件：</text>
      <view class="photo-grid mt-2">
        <view class="photo-item rounded20 colorFC6127">
          <uni-file-picker
              v-model="skillImageList"
              :auto-upload="false"
              :limit="1"
              :source-type="['album', 'camera']"
              @select="handleImageSelect($event,'business','skillImageList')"
              @delete="handleImageDelete($event,'business','skillImageList')"
              file-mediatype="image">
            <view class="d-flex d-flex-column d-flex-center" style="width: 100%;height: 100%;">
              <image
                  v-if="form.business"
                  :src="form.business"
                  mode="aspectFill"
                  style="width: 100%; height: 100%;"
              />
              <template v-else>
                <view class="placeholder" style="width: 100%; height: 100%;">
                  <image
                      mode="widthFix"
                      style="width: 100rpx"
                      class="img"
                      src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/camera.png">
                  </image>
                </view>
              </template>
            </view>
          </uni-file-picker>
        </view>
        <view class="photo-item rounded20">
          <image mode="widthFix" class="img"
                 src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/yezz.png"></image>
        </view>
      </view>
      <view class="photo-grid mt-2">
        <view class="photo-item rounded20 colorFC6127">
          <uni-file-picker
              v-model="cardImageList"
              :auto-upload="false"
              :limit="1"
              :source-type="['album', 'camera']"
              @select="handleImageSelect($event,'id_card_front','cardImageList')"
              @delete="handleImageDelete($event,'id_card_front','cardImageList')"
              file-mediatype="image">
            <view style="width: 100%; height: 100%;">
              <image
                  v-if="form.id_card_front"
                  :src="form.id_card_front"
                  mode="aspectFill"
                  style="width: 100%; height: 100%;"
              />
              <template v-else>
                <view class="placeholder" style="width: 100%; height: 100%;">
                  <text class="color666 text">身份证正面</text>
                  <image
                      mode="widthFix"
                      style="width: 100rpx"
                      class="img"
                      src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/zheng.jpg"></image>
                </view>
              </template>
            </view>
          </uni-file-picker>
        </view>
        <view class="photo-item rounded20 colorFC6127">
          <uni-file-picker
              v-model="cardBackImageList"
              :auto-upload="false"
              :limit="1"
              :source-type="['album', 'camera']"
              @select="handleImageSelect($event,'id_card_back','cardBackImageList')"
              @delete="handleImageDelete($event,'id_card_back','cardBackImageList')"
              file-mediatype="image">
            <view style="width: 100%; height: 100%;">
              <image
                  v-if="form.id_card_back"
                  :src="form.id_card_back"
                  mode="aspectFill"
                  style="width: 100%; height: 100%;"
              />
              <template v-else>
                <view class="placeholder" style="width: 100%; height: 100%;">
                  <text class="color666 text">身份证背面</text>
                  <image
                      mode="widthFix"
                      style="width: 100rpx"
                      class="img"
                      src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/fan.jpg"></image>
                </view>
              </template>
            </view>
          </uni-file-picker>
        </view>
      </view>
    </view>

    <view class="photo-section py-2">
      <text class="section-title font30 pb-1">温馨提示：</text>
      <view class="d-flex d-flex-column font22 color666">
        <text class="color666">1.信息需保证真实有效，若存在虚假信息将封禁账号。</text>
        <text class="color666"> 2.一但认证，将不可更改。</text>
        <text class="color666"> 3.信息将影响结算，请保证真实有效。</text>
        <text class="color666"> 4.违规用户的实名信息将禁止再次认证使用。</text>
        <text class="color666"> 5.实名信息将通过接口自动审核，若非出现严重违规情况，人工不介入查看。</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <button class="submit-btn font30"  @click="handleSubmit">
      提交认证
    </button>
  </view>
</template>

<script>
import {
  fileApi
} from '@/http/fileApi.js';

export default {
  data() {
    return {
      form: {
        name: '',
        business: '',
        id_card_back: '',
        id_card_front: '',
        tax_number: ''
      },
      skillImageList: [],
      cardImageList: [],

    }
  },
  onLoad() {
    this.unions()
  },
  methods: {
    async unions() {
      const res = await fileApi.getUnions();
      if (res) {
        this.form ={
          name: res.name,
          business: res.business,
          id_card_back: res.id_card_back,
          id_card_front: res.id_card_front,
          tax_number: res.tax_number
        };
      }else  {
        this.form ={
          name: '',
          business: '',
          id_card_back: '',
          id_card_front: '',
          tax_number: ''
        };
      }
    },
    async handleImageSelect(event, side, img) {
      try {
        uni.showLoading({
          title: '上传中...'
        });

        const files = event.tempFiles;
        if (files && files.length > 0) {
          const filePath = files[0].path;

          // 上传图片
          const res = await fileApi.upload(filePath);

          uni.hideLoading();

          if (res && res.data) {
            this.form[side] = res.data;
            // 更新 skillImageList 以显示已上传的图片
            this[img] = [{url: res.data}];
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        }
      } catch (err) {
        uni.hideLoading();
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.error('上传失败:', err);
      }
    },
    // 处理图片删除事件
    handleImageDelete(e, side, img) {
      this.form[side] = '';
      this[img] = [];
    },

    // 表单验证方法
    validateForm() {
      // 检查名称
      if (!this.form.name) {
        uni.showToast({
          title: '请输入名称',
          icon: 'none'
        });
        return false;
      }

      // 检查名称长度
      if (this.form.name.length < 2 || this.form.name.length > 20) {
        uni.showToast({
          title: '名称长度应为2-20个字符',
          icon: 'none'
        });
        return false;
      }

      // 检查税号
      if (!this.form.tax_number) {
        uni.showToast({
          title: '请输入税号',
          icon: 'none'
        });
        return false;
      }

      // 验证税号格式
      const taxReg = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
      if (!taxReg.test(this.form.tax_number)) {
        uni.showToast({
          title: '税号格式不正确',
          icon: 'none'
        });
        return false;
      }

      // 检查必要图片是否已上传
      if (!this.form.business) {
        uni.showToast({
          title: '请上传营业执照',
          icon: 'none'
        });
        return false;
      }

      if (!this.form.id_card_front) {
        uni.showToast({
          title: '请上传身份证正面',
          icon: 'none'
        });
        return false;
      }

      if (!this.form.id_card_back) {
        uni.showToast({
          title: '请上传身份证背面',
          icon: 'none'
        });
        return false;
      }

      return true;
    },
    async handleSubmit() {
      // 检查表单有效性
      const isValid = this.validateForm();

      if (!isValid) {
        return;
      }

      uni.showLoading({
        title: '提交中...',
        mask: true
      });

      try {
        let res = await fileApi.unionsSubmit(this.form);

        // 提交成功提示
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        });

        setTimeout(() => {
          uni.navigateBack();
        }, 1500);

      } catch (err) {
        // 优化错误处理，提供更友好的错误信息
        let errorMsg = '提交失败';

        if (err.message) {
          errorMsg = err.message;
        } else if (err.errMsg) {
          errorMsg = err.errMsg;
        }

        uni.showToast({
          title: errorMsg,
          icon: 'none'
        });

        // 输出错误信息到控制台，便于调试
        console.error('提交失败:', err);
      } finally {
        uni.hideLoading();
      }
    }
  },

}
</script>

<style scoped>
.form-row {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.label {
  width: 160rpx;
}

input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}

.section-title {
  display: block;
}

.photo-grid {
  display: flex;
  justify-content: space-between;
}

.photo-item {
  width: 48%;
  height: 240rpx;
  border: 1rpx dashed #ccc;
  overflow: hidden;
}


.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
  position: relative;
  background-color: rgba(0, 0, 0, .1);
}

.placeholder .img {
  width: 70%;
  position: absolute;
  z-index: -1;
}

.placeholder .text {
  position: absolute;
  z-index: 2;
  bottom: 5px;
}

.submit-btn {
  background: #598dfc;
  color: white;
}

.submit-btn[disabled] {
  opacity: 0.6;
}

.color598dfc {
  color: #598dfc;
}

.colorFC6127 {
  border: 1rpx dashed #FC6127;
}

.placeholder .imgIcon {
  width: 40%;
}

input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}

.photo-grid {
  display: flex;
  justify-content: space-between;
}

.photo-item {
  width: 48%;
  height: 180rpx;
  overflow: hidden;
}

.photo-item ::v-deep .uni-file-picker__container {
  width: 100%;
  height: 180rpx;
  margin: 0;
}

.photo-item ::v-deep .uni-file-picker__files {
  width: 100%;
  height: 100%;
}

.photo-item ::v-deep .file-picker__box {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  align-items: center;
  justify-content: center;
}


.photo-item ::v-deep .file-picker__box-content {
  display: flex;
  align-items: center;
  justify-content: center;
  border: none !important;
  margin: 0 !important;
}

.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #FC6127;
}

.colorFC6127 {
  border: 1rpx dashed #FC6127;
}

.placeholder .img {
  width: 30%;
}

.colorprice {
  color: #f56c22;
  margin-right: 6rpx;
}


</style>